﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace LJ.WebApi.UnifyResult.Mvc.Filters;

/// <summary>
/// 规范化结构（请求成功）过滤器
/// </summary>
public class UnifyResultFilter : IAsyncResultFilter, IOrderedFilter
{
    /// <summary>
    /// 排序属性
    /// </summary>
    public int Order => 8888;


    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        if (context.Result is ObjectResult objectResult)
        {
            if(objectResult.Value  is not WebApiResult<object>)
            {
                var result = new WebApiResult<object>
                {
                    Succeeded = true,
                    StatusCode = StatusCodes.Status200OK,
                    Data= objectResult.Value
                };
                context.Result = new ObjectResult(result);
                context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;

            }
        }
        await next();
    }
}